package org.jeecg.modules.htxincailiao.address.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.SmartBeanUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.address.domain.vo.HTAddressVO;
import org.jeecg.modules.htxincailiao.address.entity.HTBuyerAddress;
import org.jeecg.modules.htxincailiao.address.service.IHTBuyerAddressService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.htxincailiao.area.entity.HTArea;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.jeecg.modules.htxincailiao.news.entity.HTNews;
import org.jeecg.modules.htxincailiao.position.entity.HTPosition;
import org.jeecg.modules.htxincailiao.position.entity.HTPositionCategory;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ht_buyer_address
 * @Author: jeecg-boot
 * @Date:   2021-06-25
 * @Version: V1.0
 */
@Api(tags="ht_buyer_address")
@RestController
@RequestMapping("/address/hTBuyerAddress")
@Slf4j
public class HTBuyerAddressController extends JeecgController<HTBuyerAddress, IHTBuyerAddressService> {
	@Resource
	private IHTBuyerAddressService hTBuyerAddressService;

	@Resource
	private IHTAccountService accountService;

	@Resource
	private IHTAreaService areaService;

	/**
	 * 分页列表查询
	 *
	 * @param hTBuyerAddress
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-分页列表查询")
	@ApiOperation(value="ht_buyer_address-分页列表查询", notes="ht_buyer_address-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HTBuyerAddress hTBuyerAddress,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HTBuyerAddress> queryWrapper = QueryGenerator.initQueryWrapper(hTBuyerAddress, req.getParameterMap());
		Page<HTBuyerAddress> page = new Page<HTBuyerAddress>(pageNo, pageSize);
		IPage<HTBuyerAddress> pageList = hTBuyerAddressService.page(page, queryWrapper);
//		List<HTAddressVO> list =
		List<HTBuyerAddress> list = pageList.getRecords();
		List<HTAddressVO> volist = new ArrayList<>();

		for (HTBuyerAddress address: list) {
			HTAddressVO addressVO = SmartBeanUtil.copy(address, HTAddressVO.class);
			HTArea provinceArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getProvinceId())){
				provinceArea=areaService.getById(addressVO.getProvinceId());
			}
			HTArea cityArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getCityId())) {
				cityArea = areaService.getById(addressVO.getCityId());
			}
			HTArea districtArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getDistrictId())){
				districtArea = areaService.getById(addressVO.getDistrictId());
			}

			if(oConvertUtils.isNotEmpty(provinceArea) && oConvertUtils.isNotEmpty(provinceArea.getName())){
				addressVO.setProvinceName(provinceArea.getName());
			}

			if (oConvertUtils.isNotEmpty(cityArea) && oConvertUtils.isNotEmpty(cityArea.getName())){
				addressVO.setCityName(cityArea.getName());
			}
			if(oConvertUtils.isNotEmpty(districtArea) && oConvertUtils.isNotEmpty(districtArea.getName())){
				addressVO.setDistrictName(districtArea.getName());
			}
			volist.add(addressVO);
		}
		IPage<HTAddressVO> voPageList = SmartBeanUtil.copy(pageList, IPage.class);
		voPageList.setRecords(volist);

		return Result.OK(voPageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param hTBuyerAddress
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-分页列表查询")
	@ApiOperation(value="ht_buyer_address-分页列表查询", notes="ht_buyer_address-分页列表查询")
	@RequestMapping(value = "/get-user-address-list", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryPageUserAddressList(HttpServletRequest request, HTBuyerAddress hTBuyerAddress,
											  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
											  HttpServletRequest req) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}

		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)){
			if (req.getMethod().equals("POST")){
				String line = RequestUtil.getPostParam(req);
				if (oConvertUtils.isNotEmpty(line)) {
					hTBuyerAddress = JSONObject.parseObject(line, HTBuyerAddress.class);
					pageNo = oConvertUtils.isNotEmpty(hTBuyerAddress.getPageNo()) ? hTBuyerAddress.getPageNo() : pageNo;
					pageSize = oConvertUtils.isNotEmpty(hTBuyerAddress.getPageSize()) ? hTBuyerAddress.getPageSize() : pageSize;
				}
			}

			hTBuyerAddress.setBuyerId(user.getId());
			QueryWrapper<HTBuyerAddress> queryWrapper = QueryGenerator.initQueryWrapper(hTBuyerAddress, req.getParameterMap());
			Page<HTBuyerAddress> page = new Page<HTBuyerAddress>(pageNo, pageSize);
			IPage<HTBuyerAddress> pageList = hTBuyerAddressService.page(page, queryWrapper);
			return Result.OK(pageList);
		}
		else {
			return Result.error("用户不存在");
		}
	}

	/**
	 *   添加
	 *
	 * @param hTBuyerAddress
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-添加")
	@ApiOperation(value="ht_buyer_address-添加", notes="ht_buyer_address-添加")
	@PostMapping(value = "/add")
	public Result<?> add(HttpServletRequest request, @RequestBody HTBuyerAddress hTBuyerAddress) {
		hTBuyerAddressService.save(hTBuyerAddress);
		return Result.OK("添加成功！");
	}

	/**
	 *   添加
	 *
	 * @param hTBuyerAddress
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-添加")
	@ApiOperation(value="ht_buyer_address-添加", notes="ht_buyer_address-添加")
	@PostMapping(value = "/add-user-address")
	@Transactional()
	public Result<?> userAddAddress(HttpServletRequest request, @RequestBody HTBuyerAddress hTBuyerAddress) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)){
			hTBuyerAddress.setBuyerId(user.getId());
		}

		if (oConvertUtils.isNotEmpty(hTBuyerAddress.getIsDefault()) && hTBuyerAddress.getIsDefault()) {
			List<HTBuyerAddress> list = hTBuyerAddressService.findAllByIsDefault(1);
			boolean updateSucceed = false;
			for (HTBuyerAddress address: list) {
				address.setIsDefault(false);
				updateSucceed = hTBuyerAddressService.updateById(address);
				if (!updateSucceed) {
					return Result.error("更新失败！");
				}
			}
		}


		hTBuyerAddressService.save(hTBuyerAddress);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hTBuyerAddress
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-编辑")
	@ApiOperation(value="ht_buyer_address-编辑", notes="ht_buyer_address-编辑")
	@PostMapping(value = "/set-user-default-address")
	@Transactional()
	public Result<?> setDefault(HttpServletRequest request, @RequestBody HTBuyerAddress hTBuyerAddress) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}

		if (oConvertUtils.isNotEmpty(hTBuyerAddress.getIsDefault()) && hTBuyerAddress.getIsDefault()) {
			List<HTBuyerAddress> list = hTBuyerAddressService.findAllByIsDefault(1);
			// 打印所有数组元素
			boolean updateSucceed = false;
			for (HTBuyerAddress address: list) {
				address.setIsDefault(false);
				updateSucceed = hTBuyerAddressService.updateById(address);
				if (!updateSucceed) {
					return Result.error("更新失败！");
				}
			}

			boolean succeed = hTBuyerAddressService.updateById(hTBuyerAddress);
			if (succeed){
				return Result.OK("编辑成功!");
			}
			else {
				return Result.error("更新失败！");
			}
		}
		else
		{
			return Result.error("更新对象不能为空");
		}
	}

	/**
	 *  编辑
	 *
	 * @param hTBuyerAddress
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-编辑")
	@ApiOperation(value="ht_buyer_address-编辑", notes="ht_buyer_address-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTBuyerAddress hTBuyerAddress) {

		hTBuyerAddressService.updateById(hTBuyerAddress);
		return Result.OK("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param hTBuyerAddress
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-编辑")
	@ApiOperation(value="ht_buyer_address-编辑", notes="ht_buyer_address-编辑")
	@RequestMapping(value = "/edit-user-address", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> editUserAddress(HttpServletRequest request, @RequestBody HTBuyerAddress hTBuyerAddress) {
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}
		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)){
			hTBuyerAddress.setBuyerId(user.getId());
		}

		if (oConvertUtils.isNotEmpty(hTBuyerAddress.getIsDefault()) && hTBuyerAddress.getIsDefault()) {
			List<HTBuyerAddress> list = hTBuyerAddressService.findAllByIsDefault(1);
			boolean updateSucceed = false;
			for (HTBuyerAddress address: list) {
				address.setIsDefault(false);
				updateSucceed = hTBuyerAddressService.updateById(address);
				if (!updateSucceed) {
					return Result.error("更新失败！");
				}
			}
		}


		hTBuyerAddressService.updateById(hTBuyerAddress);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-通过id删除")
	@ApiOperation(value="ht_buyer_address-通过id删除", notes="ht_buyer_address-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hTBuyerAddressService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-通过id删除")
	@ApiOperation(value="ht_buyer_address-通过id删除", notes="ht_buyer_address-通过id删除")
	@RequestMapping(value = "/delete-user-address", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> deleteUserAddress(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}


		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user)){
			if (req.getMethod().equals("POST")){
				String line = RequestUtil.getPostParam(req);
				if (oConvertUtils.isNotEmpty(line)) {
					HTBuyerAddress hTBuyerAddress  = JSONObject.parseObject(line, HTBuyerAddress.class);
					id = hTBuyerAddress.getId();
				}
			}

			if(hTBuyerAddressService.removeById(id)) {
				return Result.OK("删除成功!");
			}
			else {
				return Result.error("删除失败！");
			}

		}
		else {
			return Result.error("用户不存在");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-批量删除")
	@ApiOperation(value="ht_buyer_address-批量删除", notes="ht_buyer_address-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hTBuyerAddressService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-通过id查询")
	@ApiOperation(value="ht_buyer_address-通过id查询", notes="ht_buyer_address-通过id查询")
	@RequestMapping(value = "/get-user-address-info", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> getUserAddressInfo(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		if (oConvertUtils.isEmpty(token)) {
			return Result.error("请选登录！");
		}


		String username = JwtUtil.getUsername(token);
		HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
		if (oConvertUtils.isNotEmpty(user))	{
			if (req.getMethod().equals("POST")){
				String line = RequestUtil.getPostParam(req);
				if (oConvertUtils.isNotEmpty(line)) {
					HTBuyerAddress hTBuyerAddress  = JSONObject.parseObject(line, HTBuyerAddress.class);
					id = hTBuyerAddress.getId();
				}
			}

			HTBuyerAddress hTBuyerAddress = hTBuyerAddressService.getById(id);

			HTAddressVO addressVO = SmartBeanUtil.copy(hTBuyerAddress, HTAddressVO.class);
			HTArea provinceArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getProvinceId())){
				provinceArea=areaService.getById(addressVO.getProvinceId());
			}
			HTArea cityArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getCityId())) {
				cityArea = areaService.getById(addressVO.getCityId());
			}
			HTArea districtArea = null;
			if(oConvertUtils.isNotEmpty(addressVO.getDistrictId())){
				districtArea = areaService.getById(addressVO.getDistrictId());
			}

			if(oConvertUtils.isNotEmpty(provinceArea) && oConvertUtils.isNotEmpty(provinceArea.getName())){
				addressVO.setProvinceName(provinceArea.getName());
			}

			if (oConvertUtils.isNotEmpty(cityArea) && oConvertUtils.isNotEmpty(cityArea.getName())){
				addressVO.setCityName(cityArea.getName());
			}
			if(oConvertUtils.isNotEmpty(districtArea) && oConvertUtils.isNotEmpty(districtArea.getName())){
				addressVO.setDistrictName(districtArea.getName());
			}
			if(hTBuyerAddress==null) {
				return Result.error("未找到对应数据");
			}
			return Result.OK(addressVO);
		}else {
			return Result.error("用户不存在！");
		}

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_buyer_address-通过id查询")
	@ApiOperation(value="ht_buyer_address-通过id查询", notes="ht_buyer_address-通过id查询")
	@RequestMapping(value = "/queryById", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryById(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				HTBuyerAddress hTBuyerAddress  = JSONObject.parseObject(line, HTBuyerAddress.class);
				id = hTBuyerAddress.getId();
			}
		}

		HTBuyerAddress hTBuyerAddress = hTBuyerAddressService.getById(id);
		if(hTBuyerAddress==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTBuyerAddress);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param hTBuyerAddress
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HTBuyerAddress hTBuyerAddress) {
		return super.exportXls(request, hTBuyerAddress, HTBuyerAddress.class, "ht_buyer_address");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, HTBuyerAddress.class);
	}

}
